package cn.edu.cqut.controller;

import java.util.Arrays;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import cn.edu.cqut.entity.Contact;
import cn.edu.cqut.service.IContactService;
import cn.edu.cqut.util.PageResult;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author HQYJ
 * @since 2020-06-24
 */
@RestController
@RequestMapping("/contact")
@CrossOrigin // 允许跨域请求
public class ContactController {
	@Autowired
	private IContactService contactService;
	
	@RequestMapping("/updateContact")
	public PageResult<Contact> updateContact(Contact contact) {
		contactService.updateById(contact);
		PageResult<Contact> pr = new PageResult<>();
		pr.setCode(0);
		pr.setMsg("修改客户联系人信息成功");
		return pr;
	}
	
	@RequestMapping("/addContact") 
	public PageResult<Contact> addContact(Contact contact){ 
		 contactService.save(contact);
	     PageResult<Contact> pr = new PageResult<>(); 
	     pr.setCode(0);
	     pr.setMsg("新增客户联系人成功"); 
	     return pr; 
	}
	  
	@RequestMapping("/delContact")
	public PageResult<Contact> delContact(Integer[] ids){
		 contactService.removeByIds(Arrays.asList(ids));
		 PageResult<Contact> pr = new PageResult<>();
		 pr.setCode(0);
		 pr.setMsg("删除客户联系人信息成功");
		 return pr;
	}
	
	@RequestMapping("/getCustomerContact")
	public PageResult<Contact> getCustomerContact(@RequestParam(defaultValue = "1") Integer page,
			@RequestParam(defaultValue = "10") Integer limit,Contact contact) {
		QueryWrapper<Contact> queryWapper = new QueryWrapper<>();
		queryWapper.apply("contact.cus_no=customer.cus_no");
		if (contact.getCusNo() != null) {
			queryWapper.eq("contact.cus_no", contact.getCusNo());
		}
		Page<Contact> page3 = new Page<Contact>(page, limit);
		Page<Contact> page2 = contactService.getContactWithCustomer(page3, queryWapper);
		PageResult<Contact> pr = new PageResult<>();
		pr.setCode(0);
		pr.setCount(page2.getTotal());//返回符合条件的条数
		pr.setMsg("");
		pr.setData(page2.getRecords());// 返回当前页
		return pr;
	}
}

